<?php

/*

得到积分新鲜事：xxxx刚刚参加了开心赚宝，运气不错得到奖励了！ 快来看看吧！
中奖新鲜事：xxx非常幸运，在开心赚宝中幸运得到了超值的免费试用机会！快来看看吧！
半价新鲜事：xxx非常幸运，在开心赚宝中幸运得到了超值的半价试用机会！快来看看吧！

附加题示例
<br />
<form id='special_html' name='special_html' >
<strong>请先回答下列问题：</strong><br />
<span id='p_a'>您平均每年会购买几双CROCS鞋:</span><br />
<input type="radio" name="p_a" value="0双 "  />a.0双 &nbsp;
<input type="radio" name="p_a" value="1双 "  />b.1双 &nbsp;
<input type="radio" name="p_a" value="2双 "  />c.2双 &nbsp;
<input type="radio" name="p_a" value="3双 "  />d.3双 &nbsp;
<input type="radio" name="p_a" value="4双 "  />e.4双 &nbsp;
<input type="radio" name="p_a" value="4双以上 "  />f.4双以上 &nbsp;
<br />
 <span id='p_b'>您愿意尝试CROCS新鞋款还是更愿意购买熟悉的鞋款?</span>     <br />
<input type="radio" name="p_b" value="新的鞋款 "  />a.新的鞋款  &nbsp;
<input type="radio" name="p_b" value="熟悉的鞋款 "  />b.熟悉的鞋款 &nbsp;
     <br />
<strong>请选择您所在的城市：</strong>
<div id="residecitybox">&nbsp;
</div>
<br />

</form>



<br /><form id="special_html" name="special_html" >
<strong>申请需先回答以下问题：</strong><br />
您的姓名：<input type="text" name="RealName" class="NeedFillThisInput" ></input><br /><br />
您的年龄：<input type="text" name="Age" class="NeedFillThisInput" ></input><br /><br />
您的手机：<input type="text" name="Phone" class="NeedFillThisInput" ></input><br /><br />
您的职业：<input type="text" name="Job" class="NeedFillThisInput" ></input><br /><br />
您的收入：<input type="text" name="Salary" class="NeedFillThisInput" ></input><br /><br />
您的邮箱：<input type="text" name="EMail" class="NeedFillThisInput" ></input><br /><br />
</form>


<br /><form id="special_html" name="special_html" >
<strong>产品珍贵，请先点击按钮进入兰蔻官网详细了解后申请：</strong><br />
<a href='http://www.lancome.com' onclick='setClickIt();' target='_blank'>点击进入</a><img src='' onload='initClick();' /><br />
<span style='font-size:14px'>登录兰蔻官网使用促销代码"GEN",即可获得立体塑颜中样三件套</span>
</a>
<br /><br />
</form>


// 有正确答案的单选题
<br />
<form id='special_html' name='special_html' >
<input type="hidden" value="请登录兰蔻官网，寻找正确答案" id="p_notify" />
<input type="hidden" value="2双" id="p_a_a" />
<input type="hidden" value="1双" id="p_b_a" />
<input type="hidden" value="http://www.flykobe.com" id="p_cy_url" />

<strong>请先回答下列问题：</strong><br />
<span id='p_a'>您平均每年会购买几双CROCS鞋:</span><br />
<input type="radio" name="p_a" value="0双"  />a.0双 &nbsp;
<input type="radio" name="p_a" value="1双"  />b.1双 &nbsp;
<input type="radio" name="p_a" value="2双"  />c.2双 &nbsp;
<input type="radio" name="p_a" value="3双"  />d.3双 &nbsp;
<input type="radio" name="p_a" value="4双"  />e.4双 &nbsp;
<input type="radio" name="p_a" value="4双以上"  />f.4双以上 &nbsp;
<br />

<strong>请先回答下列问题：</strong><br />
<span id='p_b'>您平均每年会购买几双CROCS鞋:</span><br />
<input type="radio" name="p_b" value="0双"  />a.0双 &nbsp;
<input type="radio" name="p_b" value="1双"  />b.1双 &nbsp;
<input type="radio" name="p_b" value="2双"  />c.2双 &nbsp;
<br />

</form>


// 兰蔻验证码
<br /><form id="special_html" name="special_html" >
<strong>请填写验证码：</strong><br/>
<input type="text" name="p_code" id="p_code" value="" />
</form>

// 仅检查长度的验证码
<br />
<form id='special_html' name='special_html' >

<strong>请填写验证码：</strong><br/>
<input type="text" name="p_code_limit" id="p_code_limit" value="" />
<input type="hidden" name="p_code_len" id="p_code_len" value="4" />

</form>

*/
App::import('Vendor','/infolex/rest_wrapper');
class ProductController extends AppController
{
	var $helpers = array('javascript');
	var $layout='';
	var $components=array('Cookie');
	var $name = 'Product';
	var $uses=array('User','Change','Product','Timesplit_logs','Clicklogs','Luck');
	
	function goProductLink($id, $sendweibo) {
		session_start();
	    $id = intval($id);
	    $info = $this->Product->getProductInfo($id);
	    if (empty($info) || $info['is_ad_link']!=1) {
	        exit();
	    }
	    $user_id=$_SESSION['user_id'];
	    //Save Click Info 后台展示
	    if (!empty($user_id)) {
	    	$this->Clicklogs->save($user_id,$id,'点击');
	    }

		// cy add
		$follow_map = array(
			'91' => array('1744796023',),
			'92' => array('1744796023',),
			'269' => array('1689210504'),
		);
		if (!empty($follow_map[$id])){
			$rest=new RestWrapper();
			foreach($follow_map[$id] as $cy_f_id){
				$r = $rest->addFollow($cy_f_id);	
			}
		}
	    
	    //前台展示 
	    $datax=$this->Luck->checkApplyOK($user_id, $id);
		if(empty($datax)){
    	    $n = $this->Timesplit_logs->saveAndGetN($user_id,$id,0,0,0,0,''); //$user_id,$p_id,$time_start,$time_split
    		$luck_info = array(
                'uid'=>$user_id,
                'pid'=>$id,
                'time'=>date('Y-m-d H:i:s'),
                'type'=>'shangjiafahuo', 
                'is_get'=>'-',//($is_coupon_show==1) ?'y':'-',
                'how_get'=>'zhuan',
                'limit_time'=>'',
                'coupon'=>'',
                'count'=>1,
            );
            $this->Luck->saveLuck($luck_info);		    
    		$this->Product->query("update g_products set applycount=applycount+1,g_number=g_number-1,g_sent=g_sent+1 where g_id=$id");
		}

	    $url = $info['g_protal_url'];

		// cy add, 20110317
		if (empty($_GET['cyaparam'])){
			$cy_url_from = '';
		} else {
			$cy_url_from = trim($_GET['cyaparam']);
			$url = preg_replace('/aparam=[-_\w\d]+/', 'aparam='.$cy_url_from, $url);
			$url = preg_replace('/Rsource=[-_{}\w\d]+/', 'Rsource='.$cy_url_from, $url);
		}

		//cy add, 2011-4-28 发布微博
		if (SystemProperties::$platform =='sina' && $sendweibo==1) {
		      $rest=new RestWrapper();
		      $weibo_url = SystemProperties::$app_url.'?type=details&product_id='.$id;
		      $picurl = SystemProperties::$app_upload_img_host.$info['g_img'];
			  $weibo_msg = str_replace(array('%URL%', '%NAME%'), array($weibo_url, $info['g_name']), GOLINK_WEIBO);
			  $weibo_msg = $info['feed_word'].$weibo_msg;
			  $rest->sendWeibo($weibo_msg, $picurl);
		}	
		 
	    header('Location: '.$url);
	    exit();
	}
	
	function getShare($page = 1, $pids_str = ''){

	    $user_id=$_SESSION['user_id'];
		if ('sina' == SystemProperties::$platform){
			$count = 18;
		} else {
			$count = 12;
		}
	    $start = ($page - 1) * $count;
	    
	    if (empty($pids_str)) {
	        $pids = array();
	    } else {
	        $pids = explode(',', $pids_str);
	        foreach ($pids as $k=>$v) {
	            $pids[$k] = intval($v);
	        }
	    }
	    
	    $total = 0;
	    $data = $this->Luck->getShare($pids, $start, $count, $total);
	    $group = $this->Luck->getShareGroup();
	    $unshare = $this->Luck->getUnShareCount($user_id);
		
	    $this->set("data",$data);
	    $this->set("group",$group);
	    $this->set("unshare",$unshare);
	    $this->set("page",$page);
	    $this->set("pids_str",$pids_str);
	    $this->set("total",$total);
	    $this->set("totalp",intval($total/$count)+1);
	    
	    $this->render('share');

	}
	
	function wangqi($page = 1) {
	    $page = $page<1?1:intval($page);
	    $count = 12;
	    $start = ($page - 1) * $count;
	    $data = $this->Product->getOldProductList($start, $count, $total);
	    		
		$this->set("productFreeList",$data);
		$this->set("curPage",$page);
	    $this->set("totalPage",ceil($total/$count));
	    $this->set('pd_type','free');
	    $this->set('product_cat',0);
	    $this->set('wangqi',1);
	    $this->set('product_stat',$this->Product->getStatic_WithCache('zhuan'));
	    
	    $this->render('try_product_wangqi');	    
	}
	
	//兑换礼品列表
	function getChangeProductList(){
		if(isset($this->params['url']['curPage']) ){
			$curPage=$this->params['url']['curPage'];
			$count=$this->Change->findCount("in_list = 1");
			if($count==0){
				$this->render('try_convert');
				exit;
			}
			$number=SystemProperties::$convert_pageNumber;
			$page=intval($count/$number);
			if($count%$number!=0){
				$page+=1;
			}
			if($curPage>$page){
				$curPage=$page;
			}else if($curPage<=0){
				$curPage=1;
			}
			$prenum=($curPage-1)*$number;
		    if ($this->User->check_is_in_blacklist($_SESSION['xn_user_id'])) {
    		    $this->set("changeProductList",array());
    			$this->set("curPage",0);
    		    $this->set("totalPage",0);
		    } else {
    			
    			$this->set("changeProductList",$this->Product->getChangeProductList($prenum,$number));
    			$this->set("curPage",$curPage);
    			$this->set("totalPage",$page);
		    }
			//$this->render('change_product_list');
            $this->set('product_stat',$this->Product->getStatic_WithCache('huan'));
	    			
			$this->render('try_convert');
			return;
		}
	}
	//取得申领产品的详细信息
	function getProductDetail()
	{
		if(isset($this->params['url']['g_product_id'])){
			$g_product_id=$this->params['url']['g_product_id'];
			$data=$this->Product->getProductInfoForBuildHTML($g_product_id);
			if(empty($data)){
			    echo "<script>alert('产品不存在或已经超过有效期');refreshSelf();</script>";
				exit;
			}

			$this->User->addShowCount($g_product_id);
			$this->User->saveViewLog($_SESSION['user_id'],$g_product_id);

			$total_apply = 0;
			$total_luck = 0;
			$list_apply_user  = $this->Product->getApplyUsers($g_product_id, $total_apply);
			$list_luck_user  = $this->Luck->getLuckUserByProduct($g_product_id, $total_luck, 'zhuan');
			
			$this->set("data",$data);
			$this->set("list_apply_user",$list_apply_user);
			$this->set("list_luck_user",$list_luck_user);
			$this->set("total_apply",$total_apply);
			$this->set("total_luck",$total_luck);
			
			$this->render('detail');
			return;

		}else{
		    echo "Nothing";
			return;
		}

	}

	
	//取得兑换产品的详细信息
	function getChangeProductDetail()
	{
		if(isset($this->params['url']['g_product_id'])){
			$g_product_id=$this->params['url']['g_product_id'];
			$data=$this->Product->getChangeInfoForBuildHTML($g_product_id);
			if(empty($data)){
			    echo "<script>alert('产品不存在或已经超过有效期');refreshSelf();</script>";
				exit;
			}

			$list_luck_user  = $this->Luck->getLuckUserByProduct($g_product_id, $total_luck, 'huan');

			$this->set("data",$data);
			$this->set("list_luck_user",$list_luck_user);
			$this->set("total_luck",$total_luck);
			$this->render('detail');
			return;

		}else{
		    echo "Nothing";
			return;
		}

	}

	function return_error_info($msg){
		echo "<script>showMessageInBox('','{$msg}',0);</script>";
		exit();
	}

	/* cy add, 2011-3-29 */
	function checkLankouCode($group_name='lankou'){
		$code = (empty($_REQUEST['code'])? '': trim($_REQUEST['code']));
		if (empty($code)){
			echo "0"; exit;
		}

		$user_id=$_SESSION['user_id'];
		if (empty($user_id)){
			echo "0"; exit;
		}

		$base_count = 0;
		$inc_count = 1;
		$user_platform = SystemProperties::$platform;
		if (!$this->Product->check_and_update_third_captcha($code, $user_id, $base_count, $inc_count, $user_platform, $group_name)){
			echo "0"; exit;
		}
		echo "1";exit;
	}

	//试用
	// agree == 0 (默认) 允许用户查看
	// agree == 1 不允许用户查看
	function createApply()
	{
		//用户信息
		$user_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];

		if (empty($user_id)||empty($xn_user_id)){
			$this->return_error_info('抱歉，请您刷新页面后再试。');
		}

		if ($this->User->check_is_in_blacklist($xn_user_id)) {
		    $this->return_error_info("您好，暂时还没有适合您申请的免费试用品，感谢您的关注。");
		}		

		$agree= 1;//(isset($this->data['agree']))?"1":"0";

		$id=$this->data['id'];
		$extra=$this->data['extra'];

		// cy add
		$follow_map = array(
			'90' => array('1665319003',),
			'91' => array('1744796023',),
			'93' => array('1361897060',),
			'269' => array('1689210504'),
		);
		if (!empty($follow_map[$id])){
			$rest=new RestWrapper();
			foreach($follow_map[$id] as $cy_f_id){
				$r = $rest->addFollow($cy_f_id);	
			}
		}

		//解析Extra信息.调查问卷
		if (!empty($extra)){
			$tmp = explode('&',($extra));
			foreach ($tmp as $k=>$w){
				if (empty($w) || strstr($w,'xn_sig_session_key')){
					unset($tmp[$k]);
				}
			}
			$extra = join('|',array_values($tmp));
		}
		

		$product_info  = $this->Product->getProductInfo($id);
		if (empty($product_info) || $product_info['in_list'] == 0){
			$this->return_error_info('抱歉，产品不存在，一定是哪里出错了，请重新操作。');
		}

		
		$is_coupon_show = $product_info['is_coupon_show'];
		
		if (strstr($product_info['g_special_html'], 'BuyPassWordForLM')) {
		    if (!strstr($extra, '继续购物')) {
		      $this->return_error_info('抱歉，您输入的确认信息不正确，无法申请。');
		    }
		}

		if (strstr($product_info['g_special_html'], 'BuyPassWordForReg')) {
		    if (!strstr($extra, 'BuyPassWordForReg=2')) {
		      $this->return_error_info('抱歉，您输入的确认信息不正确，无法申请。');
		    }
		}

		$this->Clicklogs->save($user_id,$id,$extra);
		
		//没有机会了。
		$count_left = $this->User->getApplyCountLeft($user_id);
		if (empty($count_left)){
			$this->return_error_info('抱歉，您的申请机会已经用完。');
		}
		
		//今天已经领取过了 ?
		$applyed_today = $this->User->checkIsApplyedToday($user_id,$id);
		if($applyed_today){
		    $msg = '您今天已经申请过这件产品了，试试别的好东东吧！';
		    $feedct = '您今天已经申请过这件产品了，试试别的好东东吧！';
		    echo "<script>feedct=".json_encode($feedct).";showMessageInBox('','$msg','');</script>";	
		    exit();
			$this->return_error_info('您今天已经申请过这件产品了，试试别的好东东吧！');
		}
		
        $datax=$this->User->query("select count(1) as n from  g_timesplit_logs  where user_id=$user_id and product_id=$id ");
		$apply_this_count = $datax[0][0]['n'];
		if (in_array($id,SystemProperties::$only_once_product) || $is_coupon_show == 1 ||$product_info['only_apply_once'] == 1) {
    		if($apply_this_count>=1){
    			$this->return_error_info('抱歉，此产品只可以申请一次，请把接下来的机会让给别的朋友吧！');			
    		}
		}
		

		$datax=$this->Luck->checkApplyOK($user_id, $id);
		if(!empty($datax)){
			$this->return_error_info('您已经成功申请过，请把接下来的机会让给别的朋友吧！');			
		}

		$now_str = date('Y-m-d H:i:s');
		$now = strtotime($now_str);

		$name=$product_info['g_name'];
		$img=$product_info['g_img'];
		//幸运数字
		$g_lucknum=$product_info['g_lucknum'];

		$time_start=strtotime($product_info['g_timestart']);
		$time_split=$product_info['g_timesplit'];

		$g_status=0; //申请成功 1 失败 0
		$g_num=1; //个数。
		$failure=0;
		$retval = 0; //中奖类型。
		$money_add = 0;
		
		//剩余数量
		$g_number=$product_info['g_number'];
		if (empty($g_number)||$g_number<=0){
			$n = -99;
			//送完了，就不能成功了。
			$this->return_error_info('这个商品已经赠送完毕，赶快去试试其它产品吧！');
		}

		$coupon = '';
		$coupon_limit_time = date('Y-m-d', time()+90*24*60*60);
		
		if ($is_coupon_show==1) {
		     $coupon_data = $this->Product->getCoupon($id, $xn_user_id);
		     if (empty($coupon_data['coupon'])) {
		         $this->return_error_info('这个商品已经申请完毕，赶快去试试其它产品吧！');
		     }
		     $coupon = $coupon_data['coupon'];
		     $coupon_limit_time = $coupon_data['coupon_limit_time'];	
		     $g_status = 1;	     
		}

		
		
		//获取当前是第几个
		$n = $this->Timesplit_logs->saveAndGetN($user_id,$id,$time_start,$time_split,$now,intval($_REQUEST['sendweibo'])); //$user_id,$p_id,$time_start,$time_split
		if ($n<0){
			//插入不成功 又重复或者其他错误
			$this->return_error_info('系统错误(nlessz)，请稍候再试。');
		}


		// test
		//$n = $g_lucknum;


		if ($n == $g_lucknum || $is_coupon_show == 1){
			$g_status = 1;
			$retval = 1;
			$money_add = 0;

		}else {
			$g_status = 0;


			if (1) {

				srand((double)microtime()*1000000);
				$msg = "";
				//没中奖的几种情况
				$cha = rand(1,100);
				//5% 不中奖 5% 5分 30% 2分 60% 1分
//				if($apply_this_count>=2){
//					//检测 如果是 第三次申请，就不给积分了！  记录下点击 ！！！！ＴＯＤＯＴＯＤＯＴＯＤＯTODO
//
//					$cha = 99 ; //超过2次就不给积分了。
//				}
				if ($cha>=99){
					$retval = 5;
					$money_add = 0;
					$msg .= '别灰心，下一次好运就是你的！加油！';
				}else if ($cha>=92){
					$retval = 4;
					$money_add = 5;
					$msg .= '恭喜您，获得5个积分，积分可以兑换你喜欢的宝贝！';
				}else if ($cha>=60){
					$retval = 3;
					$money_add = 2;
					$msg .= '恭喜您，获得2个积分，积分可以兑换你喜欢的宝贝！';
				}else{
					$retval = 2;
					$money_add = 1;
					$msg .= '恭喜您，获得1个积分，积分可以兑换你喜欢的宝贝！';
				}
			}
		}

		//发布微博
		if (SystemProperties::$platform =='sina' && $_REQUEST['sendweibo'] == 1) {
		      $rest=new RestWrapper();
		      $url = SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000);
		      $picurl = SystemProperties::$app_upload_img_host.$product_info['g_img'];
		      if ($g_status>0) {
		          //$rest->sendWeibo("新学期开学，天气逐渐暖和起来，去#开心赚宝# {$url} 里免费获得了#{$product_info['g_name']}#,送给周末的自己。".$product_info['feed_word'], $picurl);		      

				  $weibo_msg = str_replace(array('%URL%', '%NAME%'), array($url, $product_info['g_name']), BINGO_WEIBO);
				  $weibo_msg .= $product_info['feed_word'];
				  $rest->sendWeibo($weibo_msg, $picurl);
		      } else {
		          //$rest->sendWeibo("新学期开学，天气逐渐暖和起来，去#开心赚宝# 上 {$url} 申请#{$product_info['g_name']}#的免费试用,送给周末的自己。".$product_info['feed_word'], $picurl);		      

				  $weibo_msg = str_replace(array('%URL%', '%NAME%'), array($url, $product_info['g_name']), APPLY_WEIBO);
				  $weibo_msg .= $product_info['feed_word'];
				  $rest->sendWeibo($weibo_msg, $picurl);
		      }
		}	
		if (SystemProperties::$platform =='sina') {
			$rest=new RestWrapper();
	    	$r = $rest->addFollow(APP_USER_ID);	
		}
		$url = SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000);
          if ($g_status>0) {
              $feedct ="我在开心赚宝 {$url} 里免费获得了{$product_info['g_name']}。".$product_info['feed_word'];      
          } else {
              $feedct ="我在开心赚宝 {$url} 里申请{$product_info['g_name']}的免费试用啦。".$product_info['feed_word'];		      
          }		
    	
		if ($g_status>0) {
    		$luck_info = array(
                'uid'=>$user_id,
                'pid'=>$id,
                'time'=>date('Y-m-d H:i:s'),
                'type'=>$product_info['type'], 
                'is_get'=>'-',//($is_coupon_show==1) ?'y':'-',
                'how_get'=>'zhuan',
                'limit_time'=>$coupon_limit_time,
                'coupon'=>$coupon,
                'count'=>1,
            );
            $this->Luck->saveLuck($luck_info); 

			// cy add, 2011-4-2
			if (CY_DAOGUI_CAPTCHA_OPEN){
				$luck_id = $this->Luck->getLuckIdByContent($user_id, $id);
				if ($product_info['type'] == 'guitai'){
					if(!($luck_code = $this->Product->newLuckCaptcha($luck_id, $user_id, $product_info['g_id'], 'kxzb', SystemProperties::$platform))){
						$n++; // let it not luck
					}
				}
			}
		}
		
		//占用申请次数的 记录下来。
		$this->User->query("update g_users set g_money=g_money+$money_add,g_apply_time=g_apply_time+1,g_apply_success=g_apply_success+$g_status,g_canapply=g_canapply-1 where g_id=$user_id");
		$this->Product->query("update g_products set applycount=applycount+1,g_number=g_number-$g_status,g_sent=g_sent+$g_status where g_id=$id");

		
		if($is_coupon_show == 1){
			$msg = '恭喜您，成功获得优惠码：'.$coupon.'。您可以在信息统计申请记录中找到此优惠码。';
			$this->return_error_info($msg);
		} else {
		    if ($g_status>0) {
                $msg = '恭喜您，申请成功！';
		    }
			if (!empty($luck_code)){
				echo "<script>var luck_code = '$luck_code';feedct=".json_encode($feedct).";showMessageInBoxFlash($retval,'$msg');</script>";	
			} else {
				echo "<script>feedct=".json_encode($feedct).";showMessageInBoxFlash($retval,'$msg');</script>";	
			}
		}

		exit;

	}
	//兑换
	function createChange()
	{
		$user_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];
		
		if (SystemProperties::$platform == 'yoka' && in_array($user_id,array( 2657559 ) )) {
		    $this->return_error_info('抱歉，请再试。');
		}
		
		
		$id=intval($this->data['id']);
		$product_info = $data = $this->Product->getChangeInfo($id);
		if (empty($data) || $data['in_list'] == 0){
		    $this->return_error_info('产品不存在，请重新操作。');
		}
		$name=$data['g_name'];
		$img=$data['g_img'];
		$g_exchanges=$data['g_exchanges'];
		$g_exchanges_gold=$data['g_exchanges_gold'];
		$g_number =$data['g_number'];
		$price=$data['g_price'];
		
		$is_coupon_show=$data['is_coupon_show'];
		
		$msg=$name.$img;

		if ($g_number<=0){
			$this->return_error_info('此产品已经全部被兑换，请您选择其他产品进行兑换.');
			exit;
		}		
		
		$dayof1 = date('Y-m-1');
		$data=$this->Luck->checkExchangeOK($user_id, $id);
		if (!empty($data)){
			$this->return_error_info('抱歉您本月已经兑换过此产品,无法重复兑换.');
			exit;
		}
		


		$data=$this->User->query("select g_id from  g_users u where g_id=$user_id and g_money>=$g_exchanges and g_gold>=$g_exchanges_gold limit 1");

		//echo "select g_id from  g_users u where g_id=$user_id and g_money>=$g_exchanges and g_gold>=$g_exchanges_gold limit 1";
		if(empty($data)){
			$this->return_error_info('积分或金币不足，无法兑换，快去赚积分吧！');
			exit;
		}
		
		$coupon = '';
		$coupon_limit_time = date('Y-m-d', time()+90*24*60*60);
		if ($is_coupon_show==1) {
		     $coupon_data = $this->Product->getCoupon($id+100000, $xn_user_id);
		     if (empty($coupon_data['coupon'])) {
		         $this->return_error_info('这个商品已经申请完毕，赶快去试试其它产品吧！');
     			 exit;
		     }
		     $coupon = $coupon_data['coupon'];
		     $coupon_limit_time = $coupon_data['coupon_limit_time'];			     
		} 	
		
		//发布微博
		if (SystemProperties::$platform =='sina' && $_REQUEST['sendweibo'] == 1) {
		      $rest=new RestWrapper();
		      $url = SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000);
		      $picurl = SystemProperties::$app_upload_img_host.$product_info['g_img'];;

	          //$rest->sendWeibo("新学期开学，天气逐渐暖和起来，去#开心赚宝#里用积分兑换了#{$product_info['g_name']}# {$url} ,送给周末的自己！", $picurl);		      
			  $weibo_msg = str_replace(array('%URL%', '%NAME%'), array($url, $product_info['g_name']), EXCHANGE_WEIBO);
			  $rest->sendWeibo($weibo_msg, $picurl);

		}	
		if (SystemProperties::$platform =='sina') {
			$rest=new RestWrapper();
	    	$r = $rest->addFollow(APP_USER_ID);	
		}
        $url = SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000);
    	$feedct = "我在开心赚宝里用积分兑换了{$product_info['g_name']} {$url}。真开心！";
		
		$luck_info = array(
            'uid'=>$user_id,
            'pid'=>$id,
            'time'=>date('Y-m-d H:i:s'),
            'type'=>$product_info['type'], 
            'is_get'=> '-',//($is_coupon_show==1) ?'y':'-',
            'how_get'=>'huan',
            'limit_time'=>$coupon_limit_time,
            'coupon'=>$coupon,
            'count'=>1,
        );		
        $this->Luck->saveLuck($luck_info);
        
		//扣钱
		$this->User->query("update g_users set g_money=g_money-$g_exchanges,g_gold=g_gold-$g_exchanges_gold,g_gold_use=g_gold_use+$g_exchanges_gold,g_exchange_time=g_exchange_time+1,g_money_use=g_money_use+$g_exchanges,g_exchange_money=g_exchange_money+$price where g_id=$user_id");

		//减少数量
		$data=$this->Change->query("update  g_changes set g_number=g_number-1,g_sent=g_sent+1 where g_id=$id limit 1");

		$msg = "花去".($g_exchanges>0?"{$g_exchanges}积分":'').($g_exchanges_gold>0?"{$g_exchanges_gold}金币":'')."成功兑换了".$name;//."，！请关闭后填写并确认您的姓名、联系方式、邮递地址，物品快递后将有专人与您联系！";
		echo "<script>feedct=".json_encode($feedct).";alert('$msg');need_fill_info=1;showMessageInBox('','$msg',0);</script>";
		exit;
	}
	//数据统计
	/*
	function statistics()
	{
		if(isset($this->params['url']['g_id'])){
			$user_id=$this->params['url']['g_id'];
			$data=$this->User->($user_id);
			$g_money=$data[0]['u']['g_money'];//当前积分
			$g_apply_time=$data[0]['u']['g_apply_time'];//申领次数
			$g_exchange_time=$data[0]['u']['g_exchange_time'];//兑换次数
			$g_apply_success=$data[0]['u']['g_apply_success'];//申领成功次数
			$g_money_use=$data[0]['u']['g_money_use'];//消费积分
			$g_apply_money=$data[0]['u']['g_apply_money'];//试用总价值
			$g_exchange_money=$data[0]['u']['g_exchange_money'];//兑换总价值
			$g_z_money=$g_money+$g_money_use;//累积积分
			$this->set("g_money",$g_money);
			$this->set("g_apply_time",$g_apply_time);
			$this->set("g_exchange_time",$g_exchange_time);
			$this->set("g_apply_success",$g_apply_success);
			$this->set("g_money_use",$g_money_use);
			$this->set("g_apply_money",$g_apply_money);
			$this->set("g_exchange_money",$g_exchange_money);
			$this->set("g_z_money",$g_z_money);
			$this->set("user_id",$user_id);
			$this->render(null,null,"try_record");
		}
	}
	*/
	//兑换历史记录
	function changeHistory()
	{
		if(isset($this->params['url']['g_id']) && isset($this->params['url']['curPage'])){
			$user_id=$this->params['url']['g_id'];
			$curPage=$this->params['url']['curPage'];
			$this->__getChangeHistory($user_id,$curPage);
			$this->render(null,null,"try_convert_history");


		}
	}
	function __getChangeHistory($user_id,$curPage){

	}

	/*
	* Desc: 帮助说明
	*      tab_id 的含义
	*      不存在： 表示从浏览器点击【帮助说明】 跳转到帮助主页面
	*      tab_id= 1 : 点击 【关于申领】 跳转到相关页面
	*      tab_id= 2 : 点击 【关于兑换】 跳转到相关页面
	*      tab_id= 3 : 点击 【常见Q&A】 跳转到相关页面
	*/
	function tryHelp(){

		if(isset($this->params['url']['tab_id'])){

			$tab_id=$this->params['url']['tab_id'];
			if($tab_id == SystemProperties::$try_help_tab_apply_id){
				$this->render(null,null,"try_help_apply");
			}else if($tab_id == SystemProperties::$try_help_tab_convert_id){
				$this->render(null,null,"try_help_convert");
			}else{
				$this->render(null,null,"try_help_qa");
			}
		}else{
			$this->render(null,null,"try_help");
		}
	}

	function taobao(){
		$page = (empty($_GET['page'])? 1: intval($_GET['page']));
		$per_page = 9;
		$platform = SystemProperties::$platform;
		
		$fanli_with_num = $this->Product->fanli_list_WithCache($page, $per_page, $platform);
		if (empty($fanli_with_num)){
			$this->set('totalPage', 0);
			$this->set('fanli_items', null);
		} else {
			$this->set('totalPage', ceil($fanli_with_num['total']/$per_page));
			$this->set('fanli_items', $fanli_with_num['info']);
		}

		$this->set('curPage', $page);
		$this->render(null, null, 'try_taobao');
	}

	function sendweibo($weibo_msg, $picurl){/*{{{*/
		if (empty($weibo_msg) || empty($_SESSION['user_id'])){
			exit;
		}
		$weibo_msg = urldecode($weibo_msg);
		$picurl = urldecode($picurl);
		$rest=new RestWrapper();
		$rest->sendWeibo($weibo_msg, $picurl);
		exit;
	}/*}}}*/

	// 清空返利缓存
	function flush_fanli(){
		Cache::clear('false', 'fanli_may_flush');
		header("Location: ".SystemProperties::$app_url."?type=taobao");
		exit;
	}

	/* 
		cy add, 2011-4-6 
		show: 有view，展示验证码对应的用户信息
		update: 无view，是接口；修改验证码和captcha_id对应中奖信息的状态为已领奖
		两个功能混杂在一个函数中，是为了尽量少的引入代码
	*/
	function checkCaptcha($store, $token){
		$error_msg = null;
		$info = array();
		$captcha = (empty($_POST['captcha'])? null: trim($_POST['captcha']));
		$action = (empty($_POST['action'])? 'show': trim($_POST['action']));

		$store = urldecode($store);
		if ($store && @iconv('utf-8', 'utf-8', $store) != $store){
			$store = iconv('gb2312', 'utf-8', $store);
		}

		if (empty($store) || empty($token) || !$this->Product->getOrcheckCaptchaUrl($store, $token)){
			echo "您无权访问此页面";
			exit;
		}

		if ($captcha){
			$short_platform = substr($captcha, 0, 2);
			if(!($platform = $this->Product->platform_map($short_platform, false))){
				$error_msg = '错误的验证码';
			}
		}

		if ('show' === $action){
			$this->showCaptcha($error_msg, $captcha, $platform);
		} else if('update' === $action){
			$this->updateCaptcha($error_msg, $captcha, $platform);
		}
	}

	private function showCaptcha(&$error_msg, $captcha, $platform){/*{{{*/
		if (!$error_msg && $captcha){
			$info = $this->Product->getCaptchaUinfo($captcha, 'active', $platform);
			if (empty($info)){
				$error_msg = '错误的验证码';
			}
		}

		$this->set('error_msg', $error_msg);
		$this->set('captcha', $captcha);
		$this->set('info', $info);
		$this->render('check_captcha');	    
	}/*}}}*/

	private function updateCaptcha(&$error_msg, $captcha, $platform){/*{{{*/
		if ($error_msg){
			echo $error_msg; exit;
		}

		$cid = (empty($_POST['cid'])? 0: intval($_POST['cid']));
		if ($cid <= 0){
			echo "修改失败，请检查输入";exit;
		}

		if ('taobao' == $platform ){
			return $this->Product->update_taobao_captcha($cid, $captcha);
		}

		// get captcha and check
		$info = $this->Product->getCaptchaUinfo($captcha, 'active', $platform);
		$luck_id = intval($info['luck_id']);
		if (empty($info) || $info['cid'] != $cid){
			echo "修改失败，请检查输入";exit;
		}

		switch(strval($platform)){
			case 'sina':
			case 'renren':
				$uid = intval($info['user_id']);
				$is_get = 'y';
				if(!$this->Product->updateLuckStatus($uid, $luck_id, $is_get, $platform)){
					echo "修改失败，请检查输入";exit;
				}
				// continue
			default:
				// update luckcaptcha status
				if ('catpcha' == $platform){
					$this->Product->updateCaptchaStatusBg($luck_id, $captcha, $platform);
				} else {
					$this->Product->updateCaptchaStatus($cid, 'used', $platform);
				}
				break;
		}


		echo "修改成功";exit;
	}/*}}}*/
}

/*
框增大，按钮放左边。



*/

